$.WishWall2 = $.WishWall2 || {};

var PreviewManager = {
	cur_color: 'green',         // 当前默认颜色为green 对应component/add.html里面的相关class
	cur_shape: 'default',       // 当前默认形状为default
	swapStyle: function(shape, color){ //.. 此方法只能传入一个有效参数！！！
		// 若改变形状
		if(shape){
			//.... 去掉原来形状样式
			//.... 改变形状样式
			PreviewManager.cur_shape = shape;
			return;
		}
		if(color){
			var $preview = $('#add_preview');
			//body
			$preview.removeClass('jquery-wish-body-' + PreviewManager.cur_shape + '-' + PreviewManager.cur_color)
					.addClass('jquery-wish-body-' + PreviewManager.cur_shape + '-' + color);
			//title
			$preview.find('div:eq(0)')
					.removeClass('jquery-wish-title-'+ PreviewManager.cur_shape + '-' + PreviewManager.cur_color)
					.addClass('jquery-wish-title-' + PreviewManager.cur_shape + '-' + color);
			//content
			$preview.find('div:eq(2)')
					.removeClass('jquery-wish-content-'+ PreviewManager.cur_shape + '-' + PreviewManager.cur_color)
					.addClass('jquery-wish-content-' + PreviewManager.cur_shape + '-' + color);
			//date
			$preview.find('div:eq(3)')
					.removeClass('jquery-wish-sender-'+ PreviewManager.cur_shape + '-' + PreviewManager.cur_color)
					.addClass('jquery-wish-sender-' + PreviewManager.cur_shape + '-' + color);
			//sender
			$preview.find('div:eq(4)')
					.removeClass('jquery-wish-date-'+ PreviewManager.cur_shape + '-' + PreviewManager.cur_color)
					.addClass('jquery-wish-date-' + PreviewManager.cur_shape + '-' + color);
					
			PreviewManager.cur_color = color;
		}
	}
}

$.extend($.WishWall2,{
	AddButtonClick: bindAddEvents
});

// 加载某形状拥有的颜色可选值
function loadWishColors(shapeId,callback){
	$.ajax({
		type: "get",
		//contentType: "application/json",
		dataType: "json",
		url: ajaxRoot + "WishHandler.ashx",
		data: { "op": "getColors", "shapeId":shapeId},
		timeout: 10000,
		cache:false,
		success: function(msg) {
			$('#add_choose-color').html('<ul></ul>');
			var colors = msg.data;
			$.each(colors, function(i, color) {
				$('#add_choose-color ul').append('<li title="'+ color.colorName + 
					'" color="' + color.value + '" name="' + color.colorId + '"></li>');
			});
			
			$('#add_choose-color li').each(function() {
				$(this).css('background-color', $(this).attr('color'));
				$(this).click(function() {
					var color = $(this).attr('name');

					PreviewManager.swapStyle(null, color);
					
					$('#add_color-value').attr('value',color);
				});
			});
			
			if(callback!=undefined){
				callback();	
			}
		}
	});
}
// 加载某类别的图片
function loadWishIcons(clsId,callback){
	$.ajax({
		type: "get",
		//contentType: "application/json",
		dataType: "json",
		url: ajaxRoot + "WishHandler.ashx",
		data: { "op": "getIcons", "clsId":clsId},
		timeout: 10000,
		cache:false,
		success: function(msg) {
			//$('#add_img-shower li').remove();
			$('#add_img-shower').html('<ul></ul>');
			var icons = msg.data;
			$.each(icons, function(i, icon) {
				$('#add_img-shower ul').append('<li><img src="' + wishImgRoot + icon.imgName +'" value="' + icon.imgName + '" /></li>');
			});
			
			$('#add_choose-img .add_img-shower').jCarouselLite({
                mouseWheel: true,
                visible: 6,
                btnNext: "#add_choose-img .nextButton",
                btnPrev: "#add_choose-img .prevButton"
            });
            // 绑定选择事件
            $('#add_choose-img img').click(function() {
				var src = $(this).attr('src');
                $('#add_preview_img').attr('src', src);
				
				$('#add_icon-value').attr('value',$(this).attr('value'));  // 切换当前选择的图片名
				
            });
			
			if(callback!=undefined){
				callback();	
			}
		}
	});
}

function bindAddEvents(){
	// 添加纸条窗体
    $('li.add').click(function() {
        $.WishWall2.showMask();
        //$.WishWall2.showLoading();
        var $opWin = $('#operations');
        $opWin.load(appRoot + 'component/add.html', null, initAdd);
		
        function initAdd() {
            // 加载完成
            //$.WishWall2.hideLoading();
            $opWin.show();
			$opWin.draggable('destroy');
            $opWin.draggable();
			
			$('#add_validate-code').validateCode({
				url: ajaxRoot + 'ValidateCodeHandler.ashx',
				type:$.WishWall2.voteValidateType[Subject.voteLimit],
				tipText: '需要输入密码，提示：'+ Subject.voteCodeTip
			});
			//************** 初始化窗体 ****************
			$('#add_applyer-words').find('div:eq(2)').text(Subject.wordsToVoter);
			$('#add_applyer-words').find('div:eq(3)').text('经纬网');   //....  需要修改
			$('#add_applyer-words').find('div:eq(4)').text(Subject.applyTime);
			
			$('#add_sender').keyup(function(){
				$('#add_preview').find('div:eq(3)').text($(this).attr('value'));
			});
			$('#add_words').keyup(function(){
				var words = $(this).attr('value');
				if (words.length > 70)
					return false;
					
				$('#add_preview-content').text(words);
				
				var left = 70 - words.length;
				$('#add_words-left').text('还剩' + left + '字');
			});
			//$(document).bind('keydown', {combi:'a', disableInInput: true}, fn3());
			
			$.ajax({
				type: "get",
				//contentType: "application/json",
				dataType: "json",
				url: ajaxRoot + "WishHandler.ashx",
				data: { "op": "initAdd"},
				timeout: 10000,
				cache:true,
				success: function(msg) {
					var shapes = msg.data.shape;
					var colors = msg.data.color;
					var iconCls = msg.data.iconCls;
					var icons = msg.data.icon;
					
					// --------------形状选择区--------------
					$('#add_choose-shape').html('');
					$.each(shapes, function(i, shape) {
						//$('#add_imgCls-selecter').append('<option value="' + c.clsId +'">' + c.clsName + '</option>');
						var radioId = 'add_shape-'+i;
						$('#add_choose-shape').append(
							'<input type="radio" id="' + 
							radioId +'" name="shape" value="' + 
							shape.shapeId + '"/><label for="' + 
							radioId + '">' + shape.name + '</label>');
						
						//<input type="radio" id="add_shape-1" name="shape" checked="checked" value="default" /><label for="add_shape-1">默认</label>
					});
					$('#add_shape-0').attr('checked','checked');
					//绑定事件
					//$('#add_choose-shape input[name="shape"]').click(function(){alert('绑定事件')});
					
					// --------------颜色选择区--------------
					$('#add_choose-color').html('<ul></ul>');
					$.each(colors, function(i, color) {
						$('#add_choose-color ul').append('<li title="'+ color.colorName + 
							'" color="' + color.value + '" name="' + color.colorId + '"></li>');
					});
					// 绑定事件
					$('#add_choose-color li').each(function() {
						$(this).css('background-color', $(this).attr('color'));
						$(this).click(function() {
							var color = $(this).attr('name');
		
							PreviewManager.swapStyle(null, color);
							
							$('#add_color-value').attr('value',color);
						});
					});
					// --------------图片分类选择区--------------
					$.each(iconCls, function(i, cls) {
						$('#add_imgCls-selecter').append('<option value="' + cls.clsId +'">' + cls.clsName + '</option>');
					});
					// 添加选择事件
					//.......
					// --------------图片选择区--------------
					$('#add_img-shower').html('<ul></ul>');
					$.each(icons, function(i, icon) {
						$('#add_img-shower ul').append('<li><img src="' + wishImgRoot + icon.imgName +'" value="' + icon.imgName + '" /></li>');
					});
					
					$('#add_choose-img .add_img-shower').jCarouselLite({
						mouseWheel: true,
						visible: 6,
						btnNext: "#add_choose-img .nextButton",
						btnPrev: "#add_choose-img .prevButton"
					});
					// 绑定选择事件
					$('#add_choose-img img').click(function() {
						var src = $(this).attr('src');
						$('#add_preview_img').attr('src', src);
						
						$('#add_icon-value').attr('value',$(this).attr('value'));  // 切换当前选择的图片名
						
					});
					$('#add_icon-value')
				}
			
			});
			
			
			//***********  颜色控制  ******************
            //var color = ;
            //alert($('#add_choose-color li').attr('color'));
            /*$('#add_choose-color li').each(function() {
                $(this).css('background-color', $(this).attr('color'));
				$(this).click(function() {
					var color = $(this).attr('name');

					PreviewManager.swapStyle(null, color);
					
					$('#add_color-value').attr('value',color);
				});
            });
*/
            /*$('#add_choose-color li').click(function() {
                PreviewManager.swapStyle(null, $(this).attr('name'));
            });*/


            //***********  图片控制  ******************
            // 加载图片分类 // 加载图片
			/*loadWishIconClass(function(){
				//此处显示窗体
				loadWishIcons(1);					   
			});*/
			
            
            // 图片滚动控制
            /*$('#add_choose-img .add_img-shower').jCarouselLite({
                mouseWheel: true,
                visible: 6,
                btnNext: "#add_choose-img .nextButton",
                btnPrev: "#add_choose-img .prevButton"
            });
            // 绑定选择事件
            $('#add_choose-img img').click(function() {
				var src = $(this).attr('src');
                $('#add_preview_img').attr('src', src);
				
				$('#add_icon-value').attr('value',$(this).attr('value'));  // 切换当前选择的图片名
				
            });*/

            //$('#add_preview_img').attr("src",wishImgRoot + 'icon0.gif');

            // 提交事件
            $('#add_form').validate({
                rules: {
                    sender: {
                        maxlength: 20,
                        required: true
                    },
                    words: {
                        maxlength: 70,
                        required: true
                    },
                    validateCode: {
                        required: true
                    }
                },
                messages: {
                    sender: {
                        maxlength: '发送者名字不能超过20个字符',
                        required: '发送者名字不能为空'
                    },
                    words: {
                        maxlength: '纸条内容长度不能超过70字符',
                        required: '纸条内容不能为空'
                    },
                    validateCode: {
                        required: '请输入验证码'
                    }
                }
            });
            $('#add_form').ajaxForm({
                beforeSubmit: function() {
                    var flag = $('#add_form').valid();
                    if (flag && $.WishWall2.validateRequest()) {
                        return true;

                    }
                    return false;
                },
                url: ajaxRoot + 'WishHandler.ashx',
                data: { "op": "add", "subject": Subject.id},
                type: 'post',
				dataType:'json',
                /*global:false,    
                beforeSend:function(){
                $.WishWall2.showLoading();   // 非并行请求
                },*/
                complete: function() {
                    //$.WishWall2.hideLoading();   // 非并行请求
                    $.WishWall2.requestFinished();
                },
                success: function(result) {
					var flag = result.success;
					if (flag==false){
						var msg = result.msg;
						$.WishWall2.showMsg(msg);
						
					}
					else{
						$opWin.hide();
						$.WishWall2.hideMask();
						
						$.fn.jWish({
							z: 0,
							id: 0,
							title: '字条编号：' + 'new',      // 标题$('input[type="radio"]')
							content: $('#add_words').val(),                        // 内容
							from: $('#add_form input[name="sender"]').val(),       // 发送人
							date: new Date(),              // 日期
							icon: $('#add_form input[name="icon"]').val(),         // 纸条图片
							area: { left: Subject.theme.areaLeft, top: Subject.theme.areaTop, right: Subject.theme.areaRight, bottom: Subject.theme.areaBottom },
							skin: getSkin($('#add_form input[name="shape"]').val(), $('#add_form input[name="color"]').val())
						}).trigger("dblclick").draggable();
						//$.WishWall2.showMsg('添加成功！');
					}
                }
            });

        }
    });	
}
